#ifndef DOWNLOADER_WINDOW_H
#define DOWNLOADER_WINDOW_H

#include <gtkmm.h>
#include <glibmm/dispatcher.h>
#include <thread>
#include <mutex>
#include <atomic>
#include <string>
#include <memory> // For std::unique_ptr

// Forward declaration
class DownloaderLogic;

class DownloaderWindow : public Gtk::Window {
public:
    DownloaderWindow();
    virtual ~DownloaderWindow();

    // 结构体，用于在线程间安全地传递UI状态
    struct UIData {
        long long current_downloaded = 0;
        long long total_size = -1;
        double percentage = 0.0; // 0.0 to 1.0 for progress bar fraction
        std::string status_message = "Idle";
        bool is_running = false; // 是否正在下载或处理
        bool is_finished = false;
        bool has_error = false;
        std::string error_message = "";

        void reset() {
            current_downloaded = 0;
            total_size = -1;
            percentage = 0.0;
            status_message = "Idle";
            is_running = false;
            is_finished = false;
            has_error = false;
            error_message = "";
        }
    };

protected:
    // Signal handlers:
    void on_start_button_clicked();
    void on_cancel_button_clicked();
    // Using FileChooserButton, no separate response handler needed

    // Slot for dispatcher notification (runs in GUI thread)
    void on_update_notification();

    // Helper to update UI widgets based on m_ui_data
    void update_ui_widgets();

    // Override close request to handle running download
    // For gtkmm-4.0, the signature might differ slightly (check docs)
    // For gtkmm-3.0:
    bool on_delete_event(GdkEventAny* event) override;

    // --- GUI Widgets ---
    Gtk::Box m_main_vbox; // Main vertical box
    Gtk::Grid m_grid;      // Grid for labels and inputs
    Gtk::Label m_url_label;
    Gtk::Entry m_url_entry;
    Gtk::Label m_threads_label;
    Gtk::SpinButton m_threads_spinbutton;
    Gtk::Label m_save_path_label;
    Gtk::FileChooserButton m_save_path_button; // Easy way to select save path
    Gtk::Box m_progress_hbox; // Box for progress bar and label
    Gtk::ProgressBar m_progress_bar;
    Gtk::Label m_status_label;
    Gtk::Box m_button_hbox;  // Box for buttons
    Gtk::Button m_start_button;
    Gtk::Button m_cancel_button;

    // --- Data shared between GUI and Logic ---
    UIData m_ui_data;
    std::mutex m_ui_data_mutex; // Protect m_ui_data

    // --- Logic & Threading ---
    std::unique_ptr<DownloaderLogic> m_downloader_logic; // Use smart pointer
    std::thread m_download_thread;
    std::atomic<bool> m_cancel_requested; // Cancellation flag

    // Dispatcher for safe UI updates from background thread
    Glib::Dispatcher m_dispatcher;
};

#endif // DOWNLOADER_WINDOW_H
